package com.i2bt.app.set;

import com.i2bt.R;
import com.i2bt.app.BaseActivity;
import com.i2bt.app.login.LoginActivity;
import com.i2bt.view.NumberProgressBar;
import com.i2bt.view.SwitchButton;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SetActivity extends BaseActivity {
	private ListView listView1, listView2, listView3;
	private TextView currentAccountTextView, downloadPathTextView;
	private static final int pictureSourceId = R.drawable.set_direction;
	private static final int switchId = R.id.set_item_switch_button;
	private static final int progressId = R.id.set_item_progress;
	private Button loginOut;
	private NumberProgressBar volumeProgress;
	private SwitchButton onlyWifiSwitch, shareSwitch;
	private String version = "v1.0";
	private String downloadPath;
	private String defultDownloadPath = "/sdcard";
	private String account;

	@Override
	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_set);
		initView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		boolean result = super.onCreateOptionsMenu(menu);
		this.setActionMenuGroupVisible(false);
		this.setActionBarBack("设置");
		return result;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		downloadPath = readXML("SETTING", "SHOWPATH");
		if (downloadPath == null) {
			downloadPath = defultDownloadPath;
		}
		downloadPathTextView.setText("选择默认下载位置	" + downloadPath);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		logic();
		listView1 = (ListView) this.findViewById(R.id.set_homebox_listview);
		this.setList(listView1,
				new String[] { "绑定HomeBox", "HomeBox容量", "权限设置" },
				new Object[] { pictureSourceId, null, pictureSourceId },
				new Object[] { null, null, null }, new Object[] { null,
						progressId, null }, 1);
		listView2 = (ListView) this.findViewById(R.id.set_simple_listview);
		this.setList(listView2, new String[] { "仅在wifi下载", "选择默认下载位置",
				"检查版本更新            " + "	" + version }, new Object[] { null,
				pictureSourceId, pictureSourceId }, new Object[] { switchId,
				null, null }, new Object[] { null, null, null }, 2);
		listView3 = (ListView) this.findViewById(R.id.set_about_listView);
		this.setList(listView3, new String[] { "分享通知", "关于", }, new Object[] {
				null, pictureSourceId }, new Object[] { switchId, null },
				new Object[] { null, null }, 3);
		listView1.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 0) {
					goActivity(BindHomeBoxActivity.class);
				} else if (arg2 == 2) {
					goActivity(AuthoritySetActivity.class);
				}
			}
		});
		listView2.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 1) {
					goActivity(FileManager.class);
				}
				if (arg2 == 2) {
					chechNewVersion();
				}
			}
		});
		listView3.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (arg2 == 1) {
					showAbout();
				}
			}
		});
		currentAccountTextView = (TextView) this
				.findViewById(R.id.set_current_account_text);
		account = this.readXML("ACCOUNT", "USERID");
		if (account == null) {
			currentAccountTextView.setText("");
		} else {
			currentAccountTextView.setText(account);
		}
		loginOut = (Button) this.findViewById(R.id.set_login_out_button);
		loginOut.setOnClickListener(this);

	}

	private void setHomeBoxVolume() {
		// TODO
	}

	private void chechNewVersion() {
		Toast.makeText(getApplicationContext(), "没有新版本", Toast.LENGTH_LONG)
				.show();
	}

	private void showAbout() {
		Toast.makeText(getApplicationContext(), "陈狗淇制作", Toast.LENGTH_LONG)
				.show();
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0 == loginOut) {
			this.removeXML("ACCOUNT", "USERID");
			this.removeXML("ACCOUNT", "PASSWORD");
			this.toastHandler("注销成功");
			this.goActivityAndFinish(LoginActivity.class);
		}
	}

	@Override
	protected void logic() {
		// TODO Auto-generated method stub
		downloadPath = readXML("SETTING", "SHOWPATH");
		if (downloadPath == null) {
			File index = Environment.getExternalStorageDirectory();
			if (index.exists()) {
				File p = new File(index.getPath() + "/Download");
				if (!p.exists()) {
					try {
						if (p.createNewFile()) {
							defultDownloadPath = p.getPath();
						} else {
							defultDownloadPath = index.getPath();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else {
				File phone = Environment.getRootDirectory();
				System.out.println(phone.getPath().toString());
				File p = new File(phone.getPath() + "/Download");
				if (!p.exists()) {
					try {
						if (p.createNewFile()) {
							defultDownloadPath = p.getPath();
						} else {
							defultDownloadPath = phone.getPath();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			downloadPath = "/Download";
			this.writeXML("SETTING", "SHOWPATH", "/Download");
			this.writeXML("SETTING", "DOWNLOADPATH", defultDownloadPath);
		}
	}

	public void setList(ListView list, String txt[], Object pic[],
			Object btu[], Object progress[], int number) {
		ArrayList<HashMap<String, Object>> listItems = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < txt.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("wenben", txt[i]);
			map.put("pic", pic[i]);
			map.put("switch", btu[i]);
			map.put("progress", progress[i]);
			listItems.add(map);
		}
		SetListViewAdapter listItemAdapter = new SetListViewAdapter(this,
				listItems, R.layout.set_list_item, new String[] { "wenben",
						"pic", "switch", "progress" }, new int[] {
						R.id.set_item_text, R.id.set_item_picture,
						R.id.set_item_switch_button, R.id.set_item_progress },
				number);
		list.setAdapter(listItemAdapter);
		setListViewHeightBasedOnChildren(list);
	}

	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.writeXMLBoolean("SETTING", "ONLYWIFI",
					onlyWifiSwitch.isChecked());
			this.writeXMLBoolean("SETTING", "SHARENOTIFICATION",
					shareSwitch.isChecked());
		}
		finish();
		return false;
	}

	class SetListViewAdapter extends BaseAdapter {
		private Context context;
		private List<? extends Map<String, ?>> mData;
		private int mResource;
		private String[] mFrom;
		private int[] mTo;
		private LayoutInflater mLayoutInflater;
		private int number;

		public SetListViewAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to, int number) {
			this.context = context;
			this.mData = data;
			this.mResource = resource;
			this.mFrom = from;
			this.mTo = to;
			this.number = number;
			this.mLayoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return this.mData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return this.mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent) {
			// TODO Auto-generated method stub
			contentView = this.mLayoutInflater.inflate(this.mResource, parent,
					false);
			TextView textView = (TextView) contentView.findViewById(mTo[0]);
			textView.setText(this.mData.get(position).get(this.mFrom[0])
					.toString());
			textView.setTextSize(15);
			if (number == 2 && position == 1) {
				downloadPathTextView = textView;
				downloadPathTextView.setText("选择默认下载位置	" + downloadPath);
			}

			ImageView img = (ImageView) contentView.findViewById(mTo[1]);
			if (this.mData.get(position).get(this.mFrom[1]) != null) {
				img.setImageDrawable(context.getResources().getDrawable(
						R.drawable.set_direction));
			}

			SwitchButton switchbtu = (SwitchButton) contentView
					.findViewById(mTo[2]);
			if (this.mData.get(position).get(this.mFrom[2]) == null) {
				switchbtu.setVisibility(View.INVISIBLE);
			} else {
				if (number == 2) {
					onlyWifiSwitch = switchbtu;
					Object wifi = readXMLBoolean("SETTING", "ONLYWIFI");
					if (wifi != null) {
						if ((Boolean) wifi) {
							onlyWifiSwitch.setChecked(true);
							System.out.println("set:"
									+ onlyWifiSwitch.isChecked());
						}
					}

				} else if (number == 3) {
					shareSwitch = switchbtu;
					Object ShareNotification = readXMLBoolean("SETTING",
							"SHARENOTIFICATION");
					if (ShareNotification != null) {
						if ((Boolean) ShareNotification) {
							shareSwitch.setChecked(true);
						}
					}

				}
				switchbtu.setVisibility(View.VISIBLE);
			}

			NumberProgressBar np = (NumberProgressBar) contentView
					.findViewById(mTo[3]);
			if (this.mData.get(position).get(this.mFrom[3]) == null) {
				np.setVisibility(View.INVISIBLE);
			} else {
				volumeProgress = np;
				volumeProgress.setProgress(20);
				setHomeBoxVolume();
				volumeProgress.setDrawText("加载中!");
				volumeProgress.setVisibility(View.VISIBLE);
			}
			return contentView;
		}
	}

	@Override
	public void backHomeOperate() {
		// TODO Auto-generated method stub
		this.writeXMLBoolean("SETTING", "ONLYWIFI", onlyWifiSwitch.isChecked());
		this.writeXMLBoolean("SETTING", "SHARENOTIFICATION",
				shareSwitch.isChecked());

		finish();
	}
}
